package com.example.megaandroidrssreader;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SourceListAdapter extends ArrayAdapter<RssSource> {

	protected ArrayList<RssSource> mRssSources;
	protected Boolean mEditMode;
	private Context mContext;
	
	public SourceListAdapter(Context context, int textViewResourceId, List<RssSource> objects, Boolean editMode) {
		super(context, textViewResourceId, objects);
		mRssSources = (ArrayList<RssSource>) objects;
		mEditMode = editMode;
		mContext = context;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View itemView = convertView;
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			itemView = inflater.inflate(R.layout.list_rss_source, parent, false);
		}

		final int pos = position;
		TextView txtRssSourceTitle = (TextView) itemView.findViewById(R.id.txtRssSourceTitle);
		txtRssSourceTitle.setText(mRssSources.get(position).mTitle);
		TextView txtRssSourceUrl = (TextView) itemView.findViewById(R.id.txtRssSourceUrl);
		txtRssSourceUrl.setText(mRssSources.get(position).mUrl);
		
		final ImageView imgRssSource = (ImageView) itemView.findViewById(R.id.imgRssSource);
		if (mRssSources.get(position).mFavicon == null) {
			imgRssSource.setImageResource(R.drawable.ic_launcher);

			// Loading favicon of RSS source site
			Pattern pattern = Pattern.compile("http://.+?/", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
			Matcher matcher = pattern.matcher(mRssSources.get(position).mUrl);
			String faviconLink = null;
			if (matcher.find()) {
				faviconLink = mRssSources.get(position).mUrl.substring(matcher.start(), matcher.end());
				faviconLink += "favicon.ico";
				AsyncTask<String, Integer, Bitmap> faviconLoader = new AsyncTask<String, Integer, Bitmap>() {

					@Override
					protected Bitmap doInBackground(String... params) {
						URL url = null;
						try {
							url = new URL(params[0]);
						} catch (MalformedURLException e) {
							e.printStackTrace();
						}
	
						HttpURLConnection connection = null;
						Bitmap favicon = null;
						try {
							connection = (HttpURLConnection) url.openConnection();
							favicon = BitmapFactory.decodeStream(connection.getInputStream());
							connection.disconnect();
						} catch (IOException e) {
							e.printStackTrace();
						}
						return favicon;
					}
	
					@Override
					protected void onPostExecute(Bitmap result) {
						super.onPostExecute(result);
						if (result != null) {
							imgRssSource.setImageBitmap(result);
							RssReaderDao dao = new RssReaderDaoImpl(mContext);
							RssSource updatedRssSource = new RssSource();
							updatedRssSource.mTitle = mRssSources.get(pos).mTitle;
							updatedRssSource.mUrl = mRssSources.get(pos).mUrl;
							updatedRssSource.mFavicon = result;
							dao.updateRssSource(mRssSources.get(pos), updatedRssSource);
							mRssSources.set(pos, updatedRssSource);
						}
					}
					
				};
				faviconLoader.execute(faviconLink);
			}
		} else {
			imgRssSource.setImageBitmap(mRssSources.get(position).mFavicon);
		}
		
		LinearLayout layoutEditSource = (LinearLayout) itemView.findViewById(R.id.layoutEditSource);
		Button btnModifySource = (Button) itemView.findViewById(R.id.btnModifySource);
		Button btnDeleteSource = (Button) itemView.findViewById(R.id.btnDeleteSource);

		if (mEditMode == Boolean.TRUE) {
			layoutEditSource.setVisibility(View.VISIBLE);
			btnModifySource.setFocusable(false);
			btnDeleteSource.setFocusable(false);
		} else {
			layoutEditSource.setVisibility(View.INVISIBLE);
		}
		
		btnModifySource.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (getContext() instanceof BaseActivity) {
					Activity activity = (Activity) getContext();
					SourceEditorFragment sourceEditorFragment = SourceEditorFragment.newInstance(false, mRssSources.get(pos), pos);
					sourceEditorFragment.show(activity.getFragmentManager(), "dialog");
				}
			}
			
		});
		
		btnDeleteSource.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				RssReaderDao dao = new RssReaderDaoImpl(mContext);
				dao.deleteRssSource(mRssSources.get(pos));
				mRssSources.remove(pos);
				SourceListAdapter.this.notifyDataSetChanged();
			}
			
		});
		
		return itemView;
	}

//	private void saveSourcesToXmlFile () {
//		File sourcesXml = new File (SourcesActivity.SOURCES_XML_FILE_NAME);
//		BufferedWriter bw = null;
//		XmlSerializer serializer = Xml.newSerializer();
//		try {
//			bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(sourcesXml), Charset.forName("UTF-8")));
//			serializer.setOutput(bw);
//			serializer.startDocument("UTF-8", true);
//			serializer.startTag("", "rss_sources");
//			for (RssSource source : mRssSources) {
//				serializer.startTag("", "source");
//				serializer.startTag("", "title");
//				serializer.text(source.mTitle);
//				serializer.endTag("", "title");
//				serializer.startTag("", "url");
//				serializer.text(source.mUrl);
//				serializer.endTag("", "url");
//				serializer.endTag("", "source");
//			}
//			serializer.endDocument();
//			bw.close();
//		} catch (IllegalArgumentException e) {
//			e.printStackTrace();
//		} catch (IllegalStateException e) {
//			e.printStackTrace();
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

}
